// 导入状态码文件
const { RES_CODE } = require('../utils/constants');

// 导入token工具包
const { verifyToken } = require('../utils/tokenUtils');

module.exports = async (req, res, next) => {

    // 单独处理预检请求
    if(req.method === 'OPTIONS'){
        next();
        return;
    }

    // 获取得到请求头中的token
    const token = req.headers['token']

    try {
        let userId = await verifyToken(token);

        // 存储 用户id
        req.userId = userId;

        next()
    } catch (e) {
        res.statusCode = 401;
        res.json({
            code: RES_CODE.DATA_ERROR,
            message: e.message
        })
    }
}
